package com.disease.api.service.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.disease.api.service.config.ReportAnnotation;
import com.disease.api.service.entity.*;
import com.disease.api.service.entity.eumns.*;
import com.disease.api.service.mapper.*;
import com.disease.api.service.model.ResponseResult;
import com.disease.api.service.model.request.DeathCardReportRequest;
import com.disease.api.service.model.request.EmrDeathInfoRequest;
import com.disease.api.service.model.request.OperateRequest;
import com.disease.api.service.model.request.PatientRequest;
import com.disease.api.service.model.response.EmrDeathInfoResponse;
import com.disease.api.service.model.response.EmrDeathListResponse;
import com.disease.api.service.model.response.TodoListResponse;
import com.disease.api.service.model.response.thirdParty.DeathCardApplyResponse;
import com.disease.api.service.model.response.thirdParty.DeathCardQueryResponse;
import com.disease.api.service.model.response.thirdParty.OAuthTokenResponse;
import com.disease.api.service.vo.EmrDeathInfoVO;
import com.disease.api.service.vo.FieldAnnotationInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeathInfoService {


    private static final DateTimeFormatter DATEFORMAT_1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATEFORMAT_2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Autowired
    private EmrDeathInfoMapper emrDeathInfoMapper;

    @Autowired
    private DeathReportInfoMapper deathReportInfoMapper;

    @Autowired
    private EmrDeathInfoResponseMapper emrDeathInfoResponseMapper;

    @Autowired
    private HospitalInfoMapper hospitalInfoMapper;

    @Autowired
    private DeathCardReportService deathCardReportService;

    @Autowired
    private DeathCardWorkFlowMapper deathCardWorkFlowMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmrActivityInfoMapper emrActivityInfoMapper;

    @Autowired
    private EmrPatientInfoMapper emrPatientInfoMapper;

    @Autowired
    EmrDeathReportInfoReviewMapper emrDeathReportInfoReviewMapper;

    @Autowired
    private CommonService commonService;


    @Scheduled(cron = "0 0 0 * * ?")
    public void todoTask() {
        updateDeathCardStatusFromDeathSystem();
    }

    private HospitalInfo hospitalInfo;

    @PostConstruct
    public void init() {
        hospitalInfo = hospitalInfoMapper.selectOne();
        if (hospitalInfo == null) {
            hospitalInfo = new HospitalInfo();
        }
    }

    public void updateHospitalInfo(HospitalInfo hospitalInfo) {
        this.hospitalInfo = hospitalInfo;
    }

    public List<EmrDeathInfo> queryEmrDeathInfo(EmrDeathInfoRequest emrDeathInfoRequest) {
        emrDeathInfoMapper.query(emrDeathInfoRequest);
        return emrDeathInfoMapper.query(emrDeathInfoRequest);
    }


    public Integer todoListCount(BaseUser user) {
        // TODO 2025/7/2 区分医生代表和公卫科代表事项
        if (user.getRole().equals(RoleEnum.DOCTOR.getRoleId())) {
            /*EmrDeathInfoRequest emrDeathInfoRequest = new EmrDeathInfoRequest();
            emrDeathInfoRequest.setDoctorId(user.getDoctorId());
            List<EmrDeathInfo> emrDeathInfos = emrDeathInfoMapper.queryList(emrDeathInfoRequest);
            Map<String, EmrDeathInfo> emrDeathInfosMap = emrDeathInfos.stream().collect(Collectors.toMap(EmrDeathInfo::getSerialNumber, info -> info, (existing, replacement) -> existing));
            // TODO 2025/7/2 查询死亡卡序列是否已提交
            List<String> seriesNums = emrDeathInfos.stream().map(EmrDeathInfo::getSerialNumber).collect(Collectors.toList());
            List<DeathReportInfo> deathReportInfoBySerialNumberList = deathReportInfoMapper.findDeathReportInfoBySerialNumberList(seriesNums);
            deathReportInfoBySerialNumberList.forEach(deathReportInfo -> {
                //删除已经提交的死亡信息
                if (emrDeathInfosMap.containsKey(deathReportInfo.getSerialNumber())) {
                    emrDeathInfosMap.remove(deathReportInfo.getSerialNumber());
                }
            });
            return emrDeathInfosMap.size();
            */
            return 0;
        } else {
            // TODO 2025/7/2 公卫科上报操作
            List<DeathReportInfo> deathReportInfos = deathReportInfoMapper.queryDeathReportInfoByStatus(Arrays.asList(StatusEnum.SUBMIT.name(), StatusEnum.RETURN.name()));
            return deathReportInfos.size();
        }
    }

    /**
     * 死亡信息列表代办信息,医生提交死亡信息，公卫审核上报两种情况，不做分页处理
     *
     * @param user
     * @param emrDeathInfoRequest
     * @return
     */
    public List<DeathReportInfo> todoList(BaseUser user, EmrDeathInfoRequest emrDeathInfoRequest) {
        List<DeathReportInfo> todoListResponses = new ArrayList<>();
        // TODO 2025/7/2 区分医生代表和公卫科代表事项
        if (user.getRole().equals(RoleEnum.DOCTOR.getRoleId())) {
            todoListResponses = new ArrayList<>();
            // TODO 2025/7/2 医生提交操作
            emrDeathInfoRequest.setDoctorId(user.getDoctorId());
            List<EmrDeathInfo> emrDeathInfos = emrDeathInfoMapper.queryList(emrDeathInfoRequest);
            // TODO 2025/7/2 查询患者身份证是否已提交
            Map<String, EmrDeathInfo> emrDeathInfosMap = emrDeathInfos.stream().collect(Collectors.toMap(EmrDeathInfo::getIdCard, info -> info, (existing, replacement) -> existing));
            List<String> idCardNums = emrDeathInfos.stream().map(EmrDeathInfo::getIdCard).collect(Collectors.toList());
            List<DeathReportInfo> deathReportInfoByIdCardList = deathReportInfoMapper.findDeathReportInfoByIdCardList(idCardNums);
            deathReportInfoByIdCardList.forEach(deathReportInfo -> {
                //删除已经提交的死亡信息
                if (emrDeathInfosMap.containsKey(deathReportInfo.getIdCard())) {
                    emrDeathInfosMap.remove(deathReportInfo.getIdCard());
                }
            });
            // TODO 2025/9/4 查询患者death_id是否已提交
            Map<String, EmrDeathInfo> emrDeathInfoIdMap = emrDeathInfosMap.values().stream().collect(Collectors.toMap(EmrDeathInfo::getId, info -> info, (existing, replacement) -> existing));
            List<String> deathIds = emrDeathInfos.stream().map(EmrDeathInfo::getId).collect(Collectors.toList());
            List<DeathReportInfo> deathReportInfoByDeathIdList = deathReportInfoMapper.findDeathReportInfoByDeathIdList(deathIds);
            deathReportInfoByDeathIdList.forEach(deathReportInfo -> {
                //删除已经提交的死亡信息
                if (emrDeathInfoIdMap.containsKey(deathReportInfo.getPkId())) {
                    emrDeathInfoIdMap.remove(deathReportInfo.getPkId());
                }
            });

            for (Map.Entry<String, EmrDeathInfo> entry : emrDeathInfoIdMap.entrySet()) {
                DeathReportInfo todoListResponse = new DeathReportInfo();
                BeanUtils.copyProperties(entry.getValue(), todoListResponse);
                todoListResponses.add(todoListResponse);
            }
        } else {
            // TODO 2025/7/2 公卫科上报操作
            todoListResponses = deathReportInfoMapper.queryDeathReportInfoByStatus(Arrays.asList(StatusEnum.SUBMIT.name(), StatusEnum.RETURN.name()));
        }
        todoListResponses.forEach(deathReportInfo -> {
            if (user.getRole().equals(RoleEnum.DOCTOR.getRoleId())) {
                deathReportInfo.setStatus(StatusEnum.UNSUBMIT.name());
            } else {
                deathReportInfo.setStatus(StatusEnum.SUBMIT.name());
            }
            deathReportInfo.setOperate(getWorkFlowOperatorByStatus(user,deathReportInfo.getStatus()));
        });

        return todoListResponses;
    }

    /**
     * 查询死因系统并更新死亡卡状态
     */
    public void updateDeathCardStatusFromDeathSystem() {
        log.info("updateDeathCardStatusFromDeathSystem start {}", DATEFORMAT_1.format(LocalDateTime.now()));
        List<DeathReportInfo> deathReportInfos = deathReportInfoMapper.queryDeathReportInfoByStatus(
                Arrays.asList(
                        StatusEnum.AUDIT.name(),
                        StatusEnum.RETURN.name(),
                        StatusEnum.AWAIT_PHC_REVIEW.name(),
                        StatusEnum.AWAIT_CDC_REVIEW.name(),
                        StatusEnum.RETURN.name(),
                        StatusEnum.CANCEL_REJECTED.name(),
                        StatusEnum.PENDING_CANCEL.name()));
        if (prePostProcess().isSuccess()) {
            for (DeathReportInfo deathReportInfo : deathReportInfos) {
                ResponseResult responseResult = deathCardReportService.queryDeathCardStatus(deathReportInfo.getCardNo());
                if (null != responseResult && responseResult.isSuccess()) {
                    if (responseResult.getCode().equals(CodeEnum.PASS.getCode()) || responseResult.getCode().equals(CodeEnum.SUCCESS.getCode())) {
                        List<DeathCardQueryResponse> deathCardQueryResponses = JSONArray.parseArray(JSONObject.toJSONString(responseResult.getData()), DeathCardQueryResponse.class);
                        if (!deathCardQueryResponses.isEmpty()) {
                            StatusEnum statusByCode = DeathSystemStatusCodeEnum.getStatusByCode(deathCardQueryResponses.get(0).getAuditFlag());
                            if (!statusByCode.name().equals(deathReportInfo.getStatus())) {
                                log.info("序列:{},死亡卡号:{},更新死亡卡状态{}", deathReportInfo.getSerialNumber(), deathReportInfo.getCardNo(), statusByCode.name());
                                //更新状态
                                Integer step = StepEnum.THREE.getIndex();
                                if (statusByCode.equals(StatusEnum.APPROVED)) {
                                    step = StepEnum.FOUR.getIndex();
                                }
                                deathReportInfoMapper.updateByPatientId(new DeathReportInfo(deathReportInfo.getPatientId(), statusByCode.name(), step));
                                //添加审批记录
                                deathCardWorkFlowMapper.insertOne(new DeathCardWorkFlow(deathReportInfo.getPatientId(), deathReportInfo.getSerialNumber(), (deathReportInfo.getApprovalStep() + 1), getWorkFlowOperatorByStatus(statusByCode).name(), "疾控", true, LocalDateTime.now(), "系统审批"));
                            }
                        }
                    }
                }
            }
        }
    }

    private OperateEnum getWorkFlowOperatorByStatus(StatusEnum status) {
        switch (status) {
            case SUBMIT:
                return OperateEnum.SUBMIT;
            case AUDIT:
                return OperateEnum.REPORT;
            case AWAIT_PHC_REVIEW:
                return OperateEnum.REVIEW;
            case AWAIT_CDC_REVIEW:
                return OperateEnum.REVIEW;
            case APPROVED:
                return OperateEnum.PASS;
            default:
                return OperateEnum.NONE;
        }
    }

    private ResponseResult prePostProcess() {
        //验证死因系统appid和appsecret是否有效
        OAuthTokenResponse oauthToken = deathCardReportService.getOauthToken();
        if (Optional.ofNullable(oauthToken.getCode()).isPresent() && !oauthToken.isSuccess()) {
            return ResponseResult.fail("死因系统appi和appkey不正确");
        } else {
            return ResponseResult.success(oauthToken);
        }
    }

    /**
     * 分页查询死亡信息
     *
     * @param pageNum
     * @param pageSize
     * @param emrDeathInfoRequest
     * @return
     */
    public PageInfo<EmrDeathListResponse> queryEmrDeathInfoByPage(BaseUser user, int pageNum, int pageSize, EmrDeathInfoRequest emrDeathInfoRequest) {
        List<EmrDeathListResponse> emrDeathInfoResponses = new ArrayList<>();
        List<EmrDeathInfo> emrDeathInfos = null;
        // TODO 2025/6/29 构造分页查询
        PageHelper.startPage(pageNum, pageSize);
        // TODO 2025/6/30 查询所有患者死亡信息
        //身份赋值，只查询临床医生关联的病人死亡信息
        if((Optional.ofNullable(emrDeathInfoRequest.getFillDoctor()).isPresent())&& !StringUtils.isBlank(emrDeathInfoRequest.getFillDoctor())){
            emrDeathInfoRequest.setChiefPhysicianName(emrDeathInfoRequest.getFillDoctor());
        }
        //放开权限查询全部数据
        if (user.getRole().equals(RoleEnum.DOCTOR.getRoleId())) {
            emrDeathInfoRequest.setDeptCode(user.getDeptCode());
            emrDeathInfos = emrDeathInfoMapper.queryList(emrDeathInfoRequest);
        } else {
            emrDeathInfos = emrDeathInfoMapper.queryList(emrDeathInfoRequest);
        }
        if (!emrDeathInfos.isEmpty()) {
            List<String> seriesNums = emrDeathInfos.stream().map(EmrDeathInfo::getSerialNumber).collect(Collectors.toList());
            List<String> idCards = emrDeathInfos.stream().map(EmrDeathInfo::getIdCard).collect(Collectors.toList());
            List<String> patientIds = emrDeathInfos.stream().map(EmrDeathInfo::getPatientId).collect(Collectors.toList());
            //todo 查询死亡上报信息
            List<DeathReportInfo> deathReportInfoBySerialNumberList = deathReportInfoMapper.findDeathReportInfoBySerialNumberOrPatientIdOrIdCard(seriesNums, patientIds, idCards);
            emrDeathInfos.forEach(emrDeathInfo -> {
                EmrDeathListResponse deathInfoResponse = new EmrDeathListResponse();
                //管理员或者公卫科需要查询填报医生信息
                if (!user.getRole().equals(RoleEnum.DOCTOR.getRoleId())&&!Optional.ofNullable(emrDeathInfo.getFillDoctor()).isPresent()) {
                    // TODO 2025/6/29 如果主治医生为空则根据就诊序列号查询emr_activity_info表中填报医生
                    List<EmrActivityInfo> emrActivityInfos = emrActivityInfoMapper.selectBySeries(seriesNums);
                    EmrActivityInfo emrActivityInfo = emrActivityInfos.stream().filter(x -> x.getSerialNumber().equals(emrDeathInfo.getSerialNumber())).findAny().orElse(null);
                    if (emrActivityInfo != null) {
                        emrDeathInfo.setOperatorId(emrActivityInfo.getOperatorId());
                        emrDeathInfo.setFillDoctor(emrActivityInfo.getFillDoctor());
                    }
                }
                BeanUtils.copyProperties(emrDeathInfo, deathInfoResponse);
                //身份证匹配是否存在手动上报情况
                DeathReportInfo deathReportInfoMatch = deathReportInfoBySerialNumberList.stream().filter(x -> {
                    if (Optional.ofNullable(x.getPkId()).isPresent() && (x.getPkId().equals(emrDeathInfo.getId()))) {
                        return true;
                    }
                    if (Optional.ofNullable(x.getIdCard()).isPresent() && (x.getIdCard().equals(emrDeathInfo.getIdCard()))) {
                        return true;
                    }
                    if (Optional.ofNullable(x.getPatientId()).isPresent() && !x.getPatientId().equals("-") && (x.getPatientId().equals(emrDeathInfo.getPatientId()))) {
                        return true;
                    }
                    if (Optional.ofNullable(x.getSerialNumber()).isPresent() && (x.getSerialNumber().equals(emrDeathInfo.getSerialNumber()))) {
                        return true;
                    }
                    return false;
                }).findFirst().orElse(null);
                if (deathReportInfoMatch != null) {
                    deathInfoResponse.setStatus(deathReportInfoMatch.getStatus());
                    //临床医生上报提交后,无操作按钮,公卫科和管理员具备操作权限
                    if (!user.getRole().equals(RoleEnum.DOCTOR.getRoleId())) {
                        deathInfoResponse.setOperate(getWorkFlowOperatorByStatus(user,deathReportInfoMatch.getStatus()));
                    } else {
                        deathInfoResponse.setOperate(OperateEnum.NONE.getOperate());
                    }
                } else {
                    deathInfoResponse.setStatus(StatusEnum.UNSUBMIT.name());
                    // TODO 2025/7/1 屏蔽医生操作按钮
                    deathInfoResponse.setOperate(getWorkFlowOperatorByStatus(user,StatusEnum.UNSUBMIT.name()));
                }
                // TODO 2025/7/11 状态筛选
                if (Optional.ofNullable(emrDeathInfoRequest.getStatus()).isPresent() && !StringUtils.isBlank(emrDeathInfoRequest.getStatus())) {
                    if (deathInfoResponse.getStatus().equals(emrDeathInfoRequest.getStatus())) {
                        emrDeathInfoResponses.add(deathInfoResponse);
                    }
                } else {
                    emrDeathInfoResponses.add(deathInfoResponse);
                }
            });
        }
        // 7. 构建分页响应对象
        PageInfo<EmrDeathListResponse> responsePageInfo = new PageInfo<>(emrDeathInfoResponses);
        // 复制分页元数据
        responsePageInfo.setTotal(emrDeathInfoResponses.size());
        return responsePageInfo;
    }

    private void handleDeathReportInfoStatusAndOperate(BaseUser user,EmrDeathInfoResponse deathInfoResponse) {
        //查询死亡卡状态
        DeathReportInfo deathReportInfoRequest = new DeathReportInfo();
        if (deathInfoResponse != null && Optional.ofNullable(deathInfoResponse.getPatientId()).isPresent() && !StringUtils.isBlank(deathInfoResponse.getPatientId()) && !deathInfoResponse.getPatientId().equals("-")) {
            deathReportInfoRequest.setPatientId(deathInfoResponse.getPatientId());
        }
        if (deathInfoResponse != null && Optional.ofNullable(deathInfoResponse.getIdcardCode()).isPresent() && !StringUtils.isBlank(deathInfoResponse.getIdcardCode()) && !deathInfoResponse.getIdcardCode().equals("-")) {
            deathReportInfoRequest.setIdCard(deathInfoResponse.getIdcardCode());
        }
        if (deathInfoResponse != null && Optional.ofNullable(deathInfoResponse.getSerialNumber()).isPresent() && !StringUtils.isBlank(deathInfoResponse.getSerialNumber()) && !deathInfoResponse.getSerialNumber().equals("-")) {
            deathReportInfoRequest.setSerialNumber(deathInfoResponse.getSerialNumber());
        }
        if (Optional.ofNullable(deathInfoResponse.getStatus()).isPresent() && !deathInfoResponse.getStatus().equals(StatusEnum.CANCELED.name())) {
            //查询没有删除记录信息
            deathReportInfoRequest.setIsDelete(0);
        }
        DeathReportInfo deathReportInfo = null;
        if (Optional.ofNullable(deathReportInfoRequest.getPatientId()).isPresent() || Optional.ofNullable(deathReportInfoRequest.getIdCard()).isPresent() || Optional.ofNullable(deathReportInfoRequest.getSerialNumber()).isPresent()) {
            deathReportInfo = deathReportInfoMapper.queryOne(deathReportInfoRequest);
        }
        if (deathReportInfo == null) {
            // TODO 2025/6/26 如果没有上报信息，则为初始状态
            deathInfoResponse.setStatus(StatusEnum.UNSUBMIT.name());
            deathInfoResponse.setOperate(getWorkFlowOperatorByStatus(user,StatusEnum.UNSUBMIT.name()));
        } else {
            //如果患者ID注销过死亡卡，并重新上报，则将canceled状态修改为未提交
            deathInfoResponse.setStatus(deathReportInfo.getStatus());
            deathInfoResponse.setOperate(getWorkFlowOperatorByStatus(user,deathInfoResponse.getStatus()));
            deathInfoResponse.setCardNo(deathReportInfo.getCardNo());
        }
        deathInfoResponse.setStepList(handleDeathWorkFlow(deathReportInfo));
        //增加是否可以编辑操作
        handleEditButton(deathInfoResponse);
    }

    public EmrDeathInfoResponse queryEmrDeathInfoByPatientId(BaseUser user, String patientId) {
        EmrDeathInfoResponse deathInfoResponse = new EmrDeathInfoResponse();
        EmrDeathInfoVO emrDeathInfoVO=null;
        DeathReportInfoReview deathReportInfoReview = emrDeathReportInfoReviewMapper.selectByQuery(DeathReportInfoReview.of(patientId, null));
        if (null != deathReportInfoReview) {
            deathInfoResponse = JSONObject.parseObject(deathReportInfoReview.getContent(), EmrDeathInfoResponse.class);
            deathInfoResponse.setPkId(deathReportInfoReview.getPkId());
        } else {
            emrDeathInfoVO = emrPatientInfoMapper.queryOne(patientId);
            if (emrDeathInfoVO != null) {
                BeanUtils.copyProperties(emrDeathInfoVO, deathInfoResponse);
                additionalDeathInfo(user, deathInfoResponse);
                additionalRegionInfo(deathInfoResponse);
            }
        }
        //设置死亡卡状态和操作码
        handleDeathReportInfoStatusAndOperate(user,deathInfoResponse);
        deathInfoResponse.setHospitalInfo(hospitalInfo);
        if(deathReportInfoReview==null && emrDeathInfoVO==null){
            additionalDeathInfo(user, deathInfoResponse);
            additionalRegionInfo(deathInfoResponse);
        }
        return deathInfoResponse;
    }

    ;

    private void handleOrgCode(EmrDeathInfoVO deathInfoResponse) {
        if (Optional.ofNullable(deathInfoResponse.getOrgCode()).isPresent() && !StringUtils.isBlank(deathInfoResponse.getOrgCode())) {
            deathInfoResponse.setCreateOrgCode(deathInfoResponse.getOrgCode());
        } else if (Optional.ofNullable(deathInfoResponse.getCreateOrgCode()).isPresent() && !StringUtils.isBlank(deathInfoResponse.getCreateOrgCode())) {
            deathInfoResponse.setOrgCode(deathInfoResponse.getCreateOrgCode());
        } else {
            deathInfoResponse.setOrgCode(Optional.ofNullable(hospitalInfo.getOrgCode()).orElse("-"));
            deathInfoResponse.setCreateOrgCode(Optional.ofNullable(hospitalInfo.getOrgCode()).orElse("-"));
        }
    }

    /**
     * 处理编辑按钮,状态为未提交、已提交、退回、注销
     *
     * @param deathInfoResponse
     */
    private void handleEditButton(EmrDeathInfoResponse deathInfoResponse) {
        if (deathInfoResponse.getStatus().equals(StatusEnum.UNSUBMIT.name()) || deathInfoResponse.getStatus().equals(StatusEnum.SUBMIT.name()) || deathInfoResponse.getStatus().equals(StatusEnum.RETURN.name()) || deathInfoResponse.getStatus().equals(StatusEnum.CANCELED.name())) {
            deathInfoResponse.setEdit(true);
        } else {
            deathInfoResponse.setEdit(false);
        }
    }

    /**
     * 根据id查询死亡信息,先查询历史是否有缓存的编辑的数据
     *
     * @param patientRequest
     * @return
     */
    public EmrDeathInfoResponse queryEmrDeathInfoById(BaseUser user, PatientRequest patientRequest) {
        EmrDeathInfoResponse deathInfoResponse = new EmrDeathInfoResponse();
        DeathReportInfoReview deathReportInfoReview=null;
        //先查询历史是否有缓存的编辑的数据
        DeathReportInfoReview deathReportInfoReviewParam = new DeathReportInfoReview();
        if( Optional.ofNullable(patientRequest.getId()).isPresent()&&!StringUtils.isBlank(patientRequest.getId()) && !patientRequest.getId().equals("-")){
            deathReportInfoReviewParam.setDeathId(patientRequest.getId());
            deathReportInfoReview=emrDeathReportInfoReviewMapper.selectByQuery(deathReportInfoReviewParam);
        }
        if(deathReportInfoReview==null && Optional.ofNullable(patientRequest.getPatientId()).isPresent()&&!StringUtils.isBlank(patientRequest.getPatientId())&&!patientRequest.getPatientId().equals("-")){
            deathReportInfoReviewParam.setDeathId(null);
            deathReportInfoReviewParam.setPatientId(patientRequest.getPatientId());
            deathReportInfoReview=emrDeathReportInfoReviewMapper.selectByQuery(deathReportInfoReviewParam);
        }
        if(deathReportInfoReview==null && Optional.ofNullable(patientRequest.getIdCard()).isPresent()&&!StringUtils.isBlank(patientRequest.getIdCard())){
            deathReportInfoReviewParam.setDeathId(null);
            deathReportInfoReviewParam.setPatientId(null);
            deathReportInfoReviewParam.setIdCard(patientRequest.getIdCard());
            deathReportInfoReview=emrDeathReportInfoReviewMapper.selectByQuery(deathReportInfoReviewParam);
        }
        //如果历史无法查询到患者信息
        if (deathReportInfoReview != null) {
            Long pkId = deathReportInfoReview.getPkId();
            deathInfoResponse = JSONObject.parseObject(deathReportInfoReview.getContent(), EmrDeathInfoResponse.class);
            deathInfoResponse.setPkId(pkId);
        } else {
            EmrDeathInfoVO emrDeathInfovo = emrDeathInfoResponseMapper.queryDeathReportInfoById(patientRequest.getId());
            if (emrDeathInfovo != null) {
                BeanUtils.copyProperties(emrDeathInfovo, deathInfoResponse);
            }
        }
        if (!Optional.ofNullable(deathInfoResponse.getId()).isPresent()) {
            deathInfoResponse.setId(patientRequest.getId());
        }
        //设置死亡卡状态和操作码
        handleDeathReportInfoStatusAndOperate(user,deathInfoResponse);
        deathInfoResponse.setHospitalInfo(hospitalInfo);
        //从缓存获取到的数据不添加额外数据
        if(deathReportInfoReview==null){
            additionalDeathInfo(user, deathInfoResponse);
            additionalRegionInfo(deathInfoResponse);
        }
        PermissionAccessService.setPermission(user, deathInfoResponse);
        return deathInfoResponse;
    }

    /**
     * 默认添加医院省市区县，方便医生填写患者住址时候默认选择本区县地址
     *
     * @param emrDeathInfoResponse
     */
    private void additionalRegionInfo(EmrDeathInfoResponse emrDeathInfoResponse) {
        RegionInfo regionInfo = emrDeathInfoResponse.getDomicileRegionInfo();
        if (null == regionInfo) {
            regionInfo = new RegionInfo();
            if (!Optional.ofNullable(regionInfo.getProvinceCode()).isPresent() && Optional.ofNullable(hospitalInfo.getProvinceCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getProvinceCode())) {
                regionInfo.setProvinceCode(hospitalInfo.getProvinceCode());
            }
            if (!Optional.ofNullable(regionInfo.getCityCode()).isPresent() && Optional.ofNullable(hospitalInfo.getCityCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getCityCode())) {
                regionInfo.setCityCode(hospitalInfo.getCityCode());
            }
            if (!Optional.ofNullable(regionInfo.getCountyCode()).isPresent() && Optional.ofNullable(hospitalInfo.getCountryCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getCountryCode())) {
                regionInfo.setCountyCode(hospitalInfo.getCountryCode());
            }
            emrDeathInfoResponse.setDomicileRegionInfo(regionInfo);
        }

        RegionInfo obodeRegionInfo = emrDeathInfoResponse.getObodeRegionInfo();//医院默认地址，用于默认填充患者地址信息，如患者没有填写地址信息，则默认填充此地址信息obodeRegionInfo
        if (null == obodeRegionInfo) {
            obodeRegionInfo = new RegionInfo();
            if (!Optional.ofNullable(obodeRegionInfo.getProvinceCode()).isPresent() && Optional.ofNullable(hospitalInfo.getProvinceCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getProvinceCode())) {
                obodeRegionInfo.setProvinceCode(hospitalInfo.getProvinceCode());
            }
            if (!Optional.ofNullable(obodeRegionInfo.getCityCode()).isPresent() && Optional.ofNullable(hospitalInfo.getCityCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getCityCode())) {
                obodeRegionInfo.setCityCode(hospitalInfo.getCityCode());
            }
            if (!Optional.ofNullable(obodeRegionInfo.getCountyCode()).isPresent() && Optional.ofNullable(hospitalInfo.getCountryCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getCountryCode())) {
                obodeRegionInfo.setCountyCode(hospitalInfo.getCountryCode());
            }
            emrDeathInfoResponse.setObodeRegionInfo(obodeRegionInfo);
        }
    }

    private List<DeathCardWorkFlow> handleDeathWorkFlow(DeathReportInfo deathReportInfo) {
        List<DeathCardWorkFlow> deathCardWorkFlows = new ArrayList<>();
        if (null != deathReportInfo) {
            if (Optional.ofNullable(deathReportInfo.getPatientId()).isPresent() && !StringUtils.isBlank(deathReportInfo.getPatientId()) && !deathReportInfo.getPatientId().equals("-")) {
                deathCardWorkFlows = deathCardWorkFlowMapper.selectByPatientId(deathReportInfo.getPatientId());
            }
            if(deathCardWorkFlows.isEmpty()&&Optional.ofNullable(deathReportInfo.getIdCard()).isPresent() && !StringUtils.isBlank(deathReportInfo.getIdCard()) && !deathReportInfo.getIdCard().equals("-")){
                //根据患者身份证ID去查询患者流程操作，因序列号不是必填项
                deathCardWorkFlows = deathCardWorkFlowMapper.selectBySerialNumber(deathReportInfo.getIdCard());
            }
            if(deathCardWorkFlows.isEmpty()&&Optional.ofNullable(deathReportInfo.getSerialNumber()).isPresent() && !StringUtils.isBlank(deathReportInfo.getSerialNumber()) && !deathReportInfo.getSerialNumber().equals("-")){
                //根据患者序列号去查询患者流程操作，因历史序列号作为关联键
                deathCardWorkFlows = deathCardWorkFlowMapper.selectBySerialNumber(deathReportInfo.getSerialNumber());
            }
            deathCardWorkFlows.forEach(deathCardWorkFlow -> {
                if ((deathCardWorkFlow.getStep() == deathReportInfo.getApprovalStep())) {
                    deathCardWorkFlow.setActive(true);
                } else {
                    deathCardWorkFlow.setActive(false);
                }
            });
        }
        switch (deathCardWorkFlows.size()) {
            case 0:
                deathCardWorkFlows.addAll(Arrays.asList(DeathCardWorkFlow.of(StepEnum.ONE.getIndex(), OperateEnum.SUBMIT.name()), DeathCardWorkFlow.of(StepEnum.TWO.getIndex(), OperateEnum.REPORT.name()), DeathCardWorkFlow.of(StepEnum.THREE.getIndex(), OperateEnum.REVIEW.name()), DeathCardWorkFlow.of(StepEnum.FOUR.getIndex(), OperateEnum.PASS.name())));
                break;
            case 1:
                deathCardWorkFlows.addAll(Arrays.asList(DeathCardWorkFlow.of(StepEnum.TWO.getIndex(), OperateEnum.REPORT.name()), DeathCardWorkFlow.of(StepEnum.THREE.getIndex(), OperateEnum.REVIEW.name()), DeathCardWorkFlow.of(StepEnum.FOUR.getIndex(), OperateEnum.PASS.name())));
                break;
            case 2:
                deathCardWorkFlows.addAll(Arrays.asList(DeathCardWorkFlow.of(StepEnum.THREE.getIndex(), OperateEnum.REVIEW.name()), DeathCardWorkFlow.of(StepEnum.FOUR.getIndex(), OperateEnum.PASS.name())));
                break;
            case 3:
                deathCardWorkFlows.add(DeathCardWorkFlow.of(StepEnum.FOUR.getIndex(), OperateEnum.PASS.name()));
                break;
            default:
                break;
        }
        return deathCardWorkFlows;
    }

    private void EnumTransform(EmrDeathInfoVO emrDeathInfoResponse) {
        //最高诊断单位转码
        if (emrDeathInfoResponse.getDiagnosticBasisCode() != null && !StringUtils.isBlank(emrDeathInfoResponse.getDiagnosticBasisCode())) {
            emrDeathInfoResponse.setDiagnosticBasisName("病理");
        }

        //最高诊断单位转码
        if (emrDeathInfoResponse.getDiagnosticUnitCode() != null && !StringUtils.isBlank(emrDeathInfoResponse.getDiagnosticUnitCode())) {
            switch (emrDeathInfoResponse.getDiagnosticUnitCode()) {
                case "1":
                    emrDeathInfoResponse.setDiagnosticUnitName("三级医院");
                    break;
                case "2":
                    emrDeathInfoResponse.setDiagnosticUnitName("二级医院");
                    break;
                case "3":
                    emrDeathInfoResponse.setDiagnosticUnitName("乡镇卫生院或社区卫生服务机构");
                    break;
                case "9":
                    emrDeathInfoResponse.setDiagnosticUnitName("其他医疗卫生机构");
            }
        }
    }


    /**
     * 获取 死亡卡报送流程
     *
     * @param user
     * @param operateRequest
     * @return
     */
    public ResponseResult operateDeathCardFLow(BaseUser user, OperateRequest operateRequest) {
        try {
            OperateEnum operateEnum = OperateEnum.valueOf(operateRequest.getOperate());
            switch (operateEnum) {
                case SUBMIT:
//                    if (!Optional.ofNullable(operateRequest.getSerialNumber()).isPresent()) {
//                        return ResponseResult.fail("请填写患者就诊序列号或住院号");
//                    }
                    return handleSubmit(user, operateRequest);
                case REPORT:
                    return handleReport(user, operateRequest);
                case CANCEL:
                    return handleCancel(user, operateRequest.getCardNo());
                case PASS:
                    return handlePass();
                default:
                    return ResponseResult.fail("不支持的操作类型: " + operateRequest.getOperate());
            }
        } catch (IllegalArgumentException e) {
            return ResponseResult.fail("无效的操作类型: " + operateRequest.getOperate());
        } catch (Exception e) {
            log.error("处理死亡卡操作时发生未知异常", e);
            return ResponseResult.fail("系统内部错误，请联系管理员");
        }
    }

    private ResponseResult handleCancel(BaseUser user, String cardNo) {
        DeathReportInfo deathReportInfo = new DeathReportInfo();
        deathReportInfo.setCardNo(cardNo);
        if (Optional.ofNullable(deathReportInfoMapper.queryOne(deathReportInfo).getCardNo()).isPresent()) {
            ResponseResult cancelDeathCardResponse = deathCardReportService.cancelDeathCard(cardNo);
            //注销申请成功后更新数据库
            if (cancelDeathCardResponse.isSuccess()) {
                deathReportInfo.setStatus(StatusEnum.CANCELED.name());
                deathReportInfo.setIsDelete(1);
                deathReportInfoMapper.updateByCardNo(deathReportInfo);
            }
            return cancelDeathCardResponse;
        } else {
            return ResponseResult.fail("死亡卡号" + cardNo + "不存在");
        }
    }

    private ResponseResult handleSubmit(BaseUser user, OperateRequest operateRequest) {
        // 获取死亡卡报告请求对象
        DeathCardReportRequest request = getDeathCardReportRequest(user, operateRequest);
        //添加提交默认信息
        request.setLoginName(hospitalInfo.getDeathSystemLoginName());
        request.setUniqueIdentifier(commonService.generatorUniqueIdentifier(hospitalInfo.getOrgCode()));
        request.setAuditFirstPerson(user.getLoginName());
        request.setAuditFirstDate(DATEFORMAT_2.format(LocalDate.now()));
        //查询历史是否存在上报的死亡卡信息
        if (Optional.ofNullable(request.getIdcardCode()).isPresent() && !StringUtils.isBlank(request.getIdcardCode())) {
            DeathReportInfo deathReportInfoRequest = DeathReportInfo.builder().idCard(request.getIdcardCode()).isDelete(0).build();
            DeathReportInfo deathReportInfo = deathReportInfoMapper.queryOne(deathReportInfoRequest);
            if (deathReportInfo != null) {
                return ResponseResult.fail("该患者已提交或已上报死亡信息,请核实");
            }
        }

        ResponseResult firstStepCheckResultResponse = validDeathCardReportRequestInfo("1", request);
        if (firstStepCheckResultResponse.isSuccess()) {
            // 公卫科医生信息
            BaseUser phUser = userMapper.select(BaseUser.PHUser());
            // 维护死亡卡主报送主表
            DeathReportInfo deathReportInfo = new DeathReportInfo();
            deathReportInfo.setPkId(Optional.ofNullable(operateRequest.getId()).orElse("-"));
            deathReportInfo.setSerialNumber(Optional.ofNullable(operateRequest.getSerialNumber()).orElse("-"));
            deathReportInfo.setPatientId(Optional.ofNullable(request.getPatientId()).orElse("-"));
            deathReportInfo.setPatientName(Optional.ofNullable(request.getName()).orElse("-"));
            deathReportInfo.setIdCard(Optional.ofNullable(request.getIdcardCode()).orElse("-"));
            deathReportInfo.setCurrentOperatorId(user.getId());
            deathReportInfo.setCurrentOperatorName(user.getUsername());
            deathReportInfo.setNextOperatorId(phUser.getId());
            deathReportInfo.setNextOperatorName(phUser.getLoginName());
            deathReportInfo.setStatus(StatusEnum.SUBMIT.name());
            deathReportInfo.setApprovalStep(StepEnum.ONE.getIndex());
            deathReportInfo.setDeathDate(request.getDeathDate());
            deathReportInfo.setFillDoctor(Optional.ofNullable(request.getDoctorName()).orElse(user.getLoginName()));
            deathReportInfo.setDeptName(Optional.ofNullable(request.getDeptName()).orElse("-"));
            deathReportInfo.setDeptCode(Optional.ofNullable(request.getDeptCode()).orElse("-"));
            deathReportInfo.setCreateDate(LocalDate.now());
            deathReportInfoMapper.insertOne(deathReportInfo);
            // 首次提交死亡卡插入审批流程
            deathCardWorkFlowMapper.insertOne(new DeathCardWorkFlow(
                    Optional.ofNullable(request.getPatientId()).orElse("-"),
                    Optional.ofNullable(request.getIdcardCode()).orElse(request.getSerialNumber()),
                    StepEnum.ONE.getIndex(),
                    OperateEnum.SUBMIT.name(),
                    user.getLoginName(),
                    false,
                    LocalDateTime.now(),
                    "医生提交死亡卡信息"
            ));
            return ResponseResult.success();
        } else {
            return firstStepCheckResultResponse;
        }
    }


    private ResponseResult handleReport(BaseUser user, OperateRequest operateRequest) {
        // 判断死因账号是否过期
        ResponseResult prePostResponseResult = prePostProcess();
        if (!prePostResponseResult.isSuccess()) {
            return prePostResponseResult;
        }

        // 获取死亡卡报告请求对象
        DeathCardReportRequest request = getDeathCardReportRequest(user, operateRequest);
        if (request == null) {
            return ResponseResult.fail("未找到匹配的死亡卡数据");
        }

        // 补充基础属性
        request.setLoginName(hospitalInfo.getDeathSystemLoginName());
        request.setUniqueIdentifier(commonService.generatorUniqueIdentifier(request.getOrgCode()));

        //去除男性死亡患者是否isPre
        if (Optional.ofNullable(request.getGender()).isPresent() && request.getGender().equals("1")) {
            request.setIsPre(null);
        }

        // 完善报告信息
//        additionalDeathInfo(user, request);

        // 查询审批流程信息并补充相关人员
//        List<DeathCardWorkFlow> workFlows = deathCardWorkFlowMapper.queryBySelect(DeathCardWorkFlow.builder().patientId(request.getPatientId()).serialNumber(request.getSerialNumber()).build());
        enhanceReportRequestWithWorkflowInfo(request);

        // 上报死亡数据
        ResponseResult<String> reportResult = reportEmrDeathCardInfo(request);
        if (!reportResult.isSuccess()) {
            return reportResult;
        }

        // 更新死亡卡主表信息
        updateDeathReportInfo(request, reportResult.getData(), user, operateRequest.getSerialNumber());

        // 提交死亡卡插入审批流程
        deathCardWorkFlowMapper.insertOne(new DeathCardWorkFlow(
                Optional.ofNullable(request.getPatientId()).orElse("-"),
                Optional.ofNullable(request.getIdcardCode()).orElse(request.getSerialNumber()),
                StepEnum.TWO.getIndex(),
                OperateEnum.REPORT.name(),
                user.getLoginName(),
                false,
                LocalDateTime.now(),
                "公卫科上报死亡卡申请"
        ));
        return ResponseResult.success();
    }

    /**
     * 获取死亡卡报告请求对象
     *
     * @param operateRequest
     * @return
     */
    private DeathCardReportRequest getDeathCardReportRequest(BaseUser user, OperateRequest operateRequest) {
        DeathReportInfoReview review = null;
        //根据身份证号码查询
        if( Optional.ofNullable(operateRequest.getIdCard()).isPresent() && !StringUtils.isBlank(operateRequest.getIdCard())){
            review = emrDeathReportInfoReviewMapper.selectByQuery(DeathReportInfoReview.builder().idCard(operateRequest.getIdCard()).build());
        }
        //根据患者ID查询
        if (review == null && Optional.ofNullable(operateRequest.getPatientId()).isPresent()&&!StringUtils.isBlank(operateRequest.getPatientId())&&!operateRequest.getPatientId().equals("-")) {
            review = emrDeathReportInfoReviewMapper.selectByQuery(DeathReportInfoReview.of(operateRequest.getPatientId(), null));
        }
        //根据ID主键查询
        if (review == null && Optional.ofNullable(operateRequest.getId()).isPresent()) {
            review = emrDeathReportInfoReviewMapper.selectByQuery(DeathReportInfoReview.of(null, operateRequest.getId()));
        }

        if (review == null&& Optional.ofNullable(operateRequest.getId()).isPresent()&&!StringUtils.isBlank(operateRequest.getId())&&!operateRequest.getPatientId().equals("-")) {
            EmrDeathInfoResponse deathInfoResponse = queryEmrDeathInfoByPatientId(user, operateRequest.getPatientId());
            if (deathInfoResponse != null) {
                review = new DeathReportInfoReview();
                review.setPatientId(operateRequest.getPatientId());
                review.setContent(JSONObject.toJSONString(deathInfoResponse));
            }
        }

        if (review != null) {
            DeathCardReportRequest request = JSONObject.parseObject(review.getContent(), DeathCardReportRequest.class);
            if (request.getCreateOrgCode() != null && !request.getCreateOrgCode().isEmpty()) {
                request.setOrgCode(request.getCreateOrgCode());
            }
            return request;
        } else if (Optional.ofNullable(operateRequest.getId()).isPresent()) {
            EmrDeathInfoVO emrDeathInfovo = emrDeathInfoResponseMapper.queryDeathReportInfoById(operateRequest.getId());
            if (emrDeathInfovo != null) {
                //设置死亡卡状态和操作码
                additionalDeathInfo(user, emrDeathInfovo);
                DeathCardReportRequest request = new DeathCardReportRequest();
                BeanUtils.copyProperties(emrDeathInfovo, request);
                return request;
            }
        }
        return null;
    }

    private void enhanceReportRequestWithWorkflowInfo(DeathCardReportRequest request) {
        request.setCreateMan(Optional.ofNullable(request.getDoctorName()).orElse(""));
        request.setReportName(Optional.ofNullable(request.getDoctorName()).orElse(""));
        request.setCreateOrgCode(request.getOrgCode());

        DeathReportInfo deathReportInfoRequest=new DeathReportInfo();
        if(null!=request.getIdcardCode()){
            deathReportInfoRequest.setIdCard(request.getIdcardCode());
        }
        if(null!=request.getPatientId()){
            deathReportInfoRequest.setPatientId(request.getPatientId());
        }
        if(null!=request.getSerialNumber()){
            deathReportInfoRequest.setSerialNumber(request.getSerialNumber());
        }
        DeathReportInfo deathReportInfoResult = queryDeathReportInfo(deathReportInfoRequest);
        if(null!=deathReportInfoResult){
            request.setAuditFirstPerson(deathReportInfoResult.getFillDoctor());
            request.setAuditFirstDate(deathReportInfoResult.getCreateDate().format(DATEFORMAT_2));
        }else {
            request.setAuditFirstPerson(request.getDoctorName());
            request.setAuditFirstDate(LocalDate.now().plusDays(2).format(DATEFORMAT_2));
        }

    }

    private void updateDeathReportInfo(DeathCardReportRequest request, String deathCardNum, BaseUser user, String serialNumber) {
        DeathReportInfo deathReportInfo = new DeathReportInfo();
        if (Optional.ofNullable(request.getId()).isPresent()) {
            deathReportInfo.setPkId(request.getId());
        }
        if (Optional.ofNullable(serialNumber).isPresent()) {
            deathReportInfo.setSerialNumber(serialNumber);
        }
        if (Optional.ofNullable(request.getPatientId()).isPresent()) {
            deathReportInfo.setPatientId(request.getPatientId());
        }
        if (Optional.ofNullable(request.getIdcardCode()).isPresent()) {
            deathReportInfo.setIdCard(request.getIdcardCode());
        }
        deathReportInfo.setFillDoctor(Optional.ofNullable(request.getDoctorName()).orElse("-"));
        deathReportInfo.setDeptName(Optional.ofNullable(request.getDeptName()).orElse("-"));
        deathReportInfo.setDeptCode(Optional.ofNullable(request.getDeptCode()).orElse("-"));
        deathReportInfo.setDeathDate(Optional.ofNullable(request.getDeathDate()).orElse("-"));
        deathReportInfo.setCardNo(deathCardNum);
        deathReportInfo.setCurrentOperatorId(user.getId());
        deathReportInfo.setCurrentOperatorName(user.getUsername());
        deathReportInfo.setNextOperatorId("-");
        deathReportInfo.setNextOperatorName("-");
        deathReportInfo.setStatus(StatusEnum.AUDIT.name());
        deathReportInfo.setApprovalStep(StepEnum.TWO.getIndex());
        deathReportInfoMapper.updateByEntity(deathReportInfo);
    }

    private ResponseResult handlePass() {
        // TODO: 实现PASS操作的业务逻辑
        return ResponseResult.success();
    }

    /**
     * 上报死亡信息接口
     *
     * @param deathCardReportRequest
     */
    public ResponseResult reportEmrDeathCardInfo(DeathCardReportRequest deathCardReportRequest) {
        deathCardReportRequest.setUniqueIdentifier(commonService.generatorUniqueIdentifier(deathCardReportRequest.getOrgCode()));
        // TODO 2025/7/1 查询历史是否存在死亡卡数据
        DeathReportInfo deathReportInfoRequest = new DeathReportInfo();
        if (deathCardReportRequest.getPatientId() != null) {
            deathReportInfoRequest.setPatientId(deathCardReportRequest.getPatientId());
        }
        if (deathCardReportRequest.getSerialNumber() != null) {
            deathReportInfoRequest.setSerialNumber(deathCardReportRequest.getSerialNumber());
        }
        if (deathCardReportRequest.getIdcardCode() != null) {
            deathReportInfoRequest.setIdCard(deathCardReportRequest.getIdcardCode());
        }
        DeathReportInfo deathReportInfo = deathReportInfoMapper.queryOne(deathReportInfoRequest);
        if (Optional.ofNullable(deathReportInfo.getCardNo()).isPresent() && !org.apache.commons.lang3.StringUtils.isBlank(deathReportInfo.getCardNo())) {
            deathCardReportRequest.setCardNo(deathReportInfo.getCardNo());
        } else {
            //获取死亡卡数据
            ResponseResult<DeathCardApplyResponse> deathCardResponseResult = deathCardReportService.generateDeathCardNum();
            if (!deathCardResponseResult.isSuccess()) {
                return deathCardResponseResult;
            } else {
                deathCardReportRequest.setCardNo(deathCardResponseResult.getData().getData().get(0).getCardNum());
            }
        }
        ResponseResult firstStepCheckResultResponse = validDeathCardReportRequestInfo("1", deathCardReportRequest);
        if (firstStepCheckResultResponse.isSuccess()) {
            //死亡信息第一联保存接口
            return deathCardReportService.reportFirstDeathInfo(deathCardReportRequest);
        } else {
            return firstStepCheckResultResponse;
        }
    }



    public PageInfo<DeathReportInfo> queryDeathCardList(Integer pageNum, Integer pageSize,BaseUser user,DeathReportInfo deathReportInfo) {
        // TODO 2025/6/29 构造分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<DeathReportInfo> deathReportInfos = deathReportInfoMapper.queryDeathCardList(deathReportInfo);
        deathReportInfos.forEach(x -> x.setOperate(getDeathCardNoOperatorByStatus(user,x.getStatus())));
        return new PageInfo<>(deathReportInfos);
    }

    private String getDeathCardNoOperatorByStatus(BaseUser user,String status) {
        switch (StatusEnum.valueOf(status)) {
            case CANCELED:
                return OperateEnum.NONE.name();
            case SUBMIT:
                return OperateEnum.NONE.name();
            case PENDING_CANCEL:
                return OperateEnum.NONE.name();
            default:
                if(!user.getRole().equals(RoleEnum.DOCTOR.getRoleId())){
                    return OperateEnum.CANCEL.name();
                }else {
                    return OperateEnum.NONE.name();
                }
        }
    }

    /**
     * 验证死亡信息上报接口参数
     *
     * @param step                   校验步骤，1：第一联上报，2：第二联上报
     * @param deathCardReportRequest
     */
    public static ResponseResult validDeathCardReportRequestInfo(String step, DeathCardReportRequest deathCardReportRequest) {
        log.info("validDeathCardReportRequestInfo:{}", JSONObject.toJSONString(deathCardReportRequest));
        //获取字段上的注解值
        List<FieldAnnotationInfo> fieldAnnotationInfos = extractAnnotatedFields(deathCardReportRequest);
        for (FieldAnnotationInfo fieldAnnotationInfo : fieldAnnotationInfos) {
            if (Arrays.asList(fieldAnnotationInfo.getStage().split(",")).contains(step) && fieldAnnotationInfo.isNotNull()) {
                if (!Optional.ofNullable(fieldAnnotationInfo.getFieldValue()).isPresent()) {
                    log.error("第一联上报数据校验 DeathCardReportRequest类 字段：" + fieldAnnotationInfo.getFieldName() + "中文含义" + fieldAnnotationInfo.getAnnotationName() + "不能为空");
                    return ResponseResult.fail(fieldAnnotationInfo.getAnnotationName() + "不能为空");
                }
            }
        }
        return ResponseResult.success();
    }

    /**
     * 获取类及其父类中带有指定注解的字段信息
     */
    private static List<FieldAnnotationInfo> extractAnnotatedFields(Object obj) {
        List<FieldAnnotationInfo> result = new ArrayList<>();
        if (obj == null) return result;

        Class<?> currentClass = obj.getClass();
        while (currentClass != null && !currentClass.equals(Object.class)) {
            for (Field field : currentClass.getDeclaredFields()) {
                ReportAnnotation annotation = field.getAnnotation(ReportAnnotation.class);
                if (annotation != null) {
                    field.setAccessible(true);
                    FieldAnnotationInfo fieldInfo = new FieldAnnotationInfo();
                    fieldInfo.setFieldName(field.getName());
                    fieldInfo.setFieldType(field.getType().getSimpleName());
                    fieldInfo.setAnnotationName(annotation.name());
                    fieldInfo.setStage(annotation.stage());
                    fieldInfo.setNotNull(annotation.notNull());

                    try {
                        // 关键修改：从传入的对象实例中获取字段值
                        fieldInfo.setFieldValue(field.get(obj));
                    } catch (Exception e) {
                        fieldInfo.setFieldValue("获取值失败: " + e.getMessage());
                    }

                    result.add(fieldInfo);
                }
            }
            currentClass = currentClass.getSuperclass();
        }
        return result;
    }

    private String getWorkFlowOperatorByStatus(BaseUser user,String status) {
        switch (StatusEnum.valueOf(status)) {
            case UNSUBMIT:
                return OperateEnum.SUBMIT.name();

            case SUBMIT:
                if(Objects.equals(user.getRole(), RoleEnum.DOCTOR.getRoleId())){
                    return OperateEnum.NONE.getOperate();
                }
                return OperateEnum.REPORT.name();

            case AUDIT:
                return OperateEnum.NONE.getOperate();

            case RETURN:
                if(Objects.equals(user.getRole(), RoleEnum.DOCTOR.getRoleId())){
                    return OperateEnum.NONE.getOperate();
                }
                return OperateEnum.REPORT.name();

            case CANCELED:
                return OperateEnum.SUBMIT.name();
            default:
                return OperateEnum.NONE.getOperate();
        }
    }

    private void additionalDeathInfo(BaseUser user, EmrDeathInfoVO emrDeathInfoVO) {
        handleOrgCode(emrDeathInfoVO);
        EnumTransform(emrDeathInfoVO);
        //性别编码设置
        if (!Optional.ofNullable(emrDeathInfoVO.getGender()).isPresent() && Optional.ofNullable(emrDeathInfoVO.getGenderName()).isPresent()) {
            if (emrDeathInfoVO.getGenderName().equals("男")) {
                emrDeathInfoVO.setGender("1");
            } else if (emrDeathInfoVO.getGenderName().equals("女")) {
                emrDeathInfoVO.setGender("2");
            } else {
                emrDeathInfoVO.setGender("9");
            }
        }
        //名族转换,默认为汉族
        if (!Optional.ofNullable(emrDeathInfoVO.getNation()).isPresent() || StringUtils.isBlank(emrDeathInfoVO.getNation())) {
            emrDeathInfoVO.setNation("01");
            emrDeathInfoVO.setNationName("汉族");
        }
        if (emrDeathInfoVO.getNation() != null && !StringUtils.isBlank(emrDeathInfoVO.getNation()) && emrDeathInfoVO.getNation().equals("1")) {
            emrDeathInfoVO.setNation("01");
        }
        //添加默认国籍
        if (!Optional.ofNullable(emrDeathInfoVO.getCountry()).isPresent() || StringUtils.isBlank(emrDeathInfoVO.getCountry())) {
            emrDeathInfoVO.setCountry("156");
            emrDeathInfoVO.setCountryName("中国");
        }

        //默认isPre为否0
        if (!Optional.ofNullable(emrDeathInfoVO.getIsPre()).isPresent() || StringUtils.isBlank(emrDeathInfoVO.getIsPre())) {
            emrDeathInfoVO.setIsPre("0");
        }

        //默认添加报送卡类型+证件类型
        if (!Optional.ofNullable(emrDeathInfoVO.getCardState()).isPresent() || StringUtils.isBlank(emrDeathInfoVO.getCardState())) {
            emrDeathInfoVO.setCardState("0");
        }
        if (!Optional.ofNullable(emrDeathInfoVO.getIdcardType()).isPresent() || StringUtils.isBlank(emrDeathInfoVO.getIdcardType())) {
            emrDeathInfoVO.setIdcardType("01");
            emrDeathInfoVO.setIdcardTypeName("居民身份证");
        }
        if (!Optional.ofNullable(emrDeathInfoVO.getGuardianIdcardType()).isPresent() || StringUtils.isBlank(emrDeathInfoVO.getGuardianIdcardType())) {
            emrDeathInfoVO.setGuardianIdcardType("01");
        }
        //添加医院机构信息
        emrDeathInfoVO.setCreateOrgCode(Optional.of(hospitalInfo.getOrgCode()).orElse("-"));
        emrDeathInfoVO.setOrgCode(Optional.of(hospitalInfo.getOrgCode()).orElse("-"));

        //添加常住村信息
        if (Optional.ofNullable(emrDeathInfoVO.getObodeVallage()).isPresent() && !StringUtils.isBlank(emrDeathInfoVO.getObodeVallage())) {
            emrDeathInfoVO.setDomicileVallage(emrDeathInfoVO.getObodeVallage());
        }
        //默认添加填报人姓名、日期
        emrDeathInfoVO.setCreateMan(user.getLoginName());
        emrDeathInfoVO.setReportName(user.getLoginName());
        emrDeathInfoVO.setDoctorName(user.getLoginName());
        emrDeathInfoVO.setCreateDate(DATEFORMAT_2.format(LocalDate.now()));
        emrDeathInfoVO.setFillCardDate(DATEFORMAT_2.format(LocalDate.now()));
        //默认患者区县为本区县
        emrDeathInfoVO.setDomicileType("01");
        //齐河医院诊断依旧为6:死后推断
        emrDeathInfoVO.setDiagnosticBasisCode("6");
        //默认最高诊断单位为本医院级别
        if (Optional.ofNullable(hospitalInfo.getOrgUnitCode()).isPresent() && !StringUtils.isBlank(hospitalInfo.getOrgUnitCode())) {
            emrDeathInfoVO.setDiagnosticUnitCode(hospitalInfo.getOrgUnitCode());
        }
    }

    public DeathReportInfo queryDeathReportInfo(DeathReportInfo deathReportInfo){
        DeathReportInfo deathReportInfoResult=null;
        DeathReportInfo deathReportInfoRequest=new DeathReportInfo();
        if(null != deathReportInfo.getIdCard()){
            deathReportInfoRequest.setIdCard(deathReportInfo.getIdCard());
            deathReportInfoResult=deathReportInfoMapper.queryOne(deathReportInfoRequest);
        }
        if(deathReportInfoResult== null && null != deathReportInfo.getPatientId()){
            deathReportInfoRequest.setIdCard(null);
            deathReportInfoRequest.setPatientId(deathReportInfo.getPatientId());
            deathReportInfoResult=deathReportInfoMapper.queryOne(deathReportInfoRequest);
        }
        if(deathReportInfoResult== null && null != deathReportInfo.getSerialNumber()){
            deathReportInfoRequest.setIdCard(null);
            deathReportInfoRequest.setPatientId(null);
            deathReportInfoRequest.setSerialNumber(deathReportInfo.getSerialNumber());
            deathReportInfoResult=deathReportInfoMapper.queryOne(deathReportInfoRequest);
        }
        return deathReportInfoResult;
    }

    public ResponseResult findRepeatCardNoByIdCard(String idCard) {
        return deathCardReportService.findRepeatCardNo(idCard);
    }
}
